function uzstring = unzerostring(uzstring, lastzero)
% unzerostring  - removed string part after first (or last) zero
%
% FORMAT:       uzstring = unzerostring(uzstring, lastzero)
%
% Input fields:
%
%       uzstring    string to be zero-char free
%       lastzero    used last zeros instead
%
% Output fields:
%
%       uzstring    zero-char removed string

% Version:  v0.8a
% Build:    9102318
% Date:     Oct-23 2008, 6:22 PM CEST
% Author:   Jochen Weber, SCAN Unit, Columbia University, NYC, NY, USA
% URL/Info: http://wiki.brainvoyager.com/BVQXtools

% argument check
if nargin < 1 || ...
   ~ischar(uzstring)
    error( ...
        'BVQXtools:BadArgument', ...
        'Invalid argument given to %s.', ...
        mfilename ...
    );
end
if isempty(uzstring)
    uzstring = '';
    return;
end
if nargin < 2 || ...
    isempty(lastzero) || ...
   (~isnumeric(lastzero) && ~islogical(lastzero)) || ...
   ~lastzero(1)
    lastzero = false;
else
    lastzero = true;
end
uzstring  = uzstring(:)';
duzstring = double(uzstring);

% for last zero
if lastzero

    % get length and find first non-zero char from end
    lzp = findfirst(duzstring ~= 0, -1);
    if isempty(lzp)
        uzstring = '';
    elseif lzp < numel(duzstring)
        uzstring(lzp+1:end) = [];
    end

% for first zero
else

    % find zeros
    fzp = findfirst(duzstring == 0);

    % return on no zeros
    if isempty(fzp)
        return;

    % return empty string if first char is zero
    elseif fzp == 1
        uzstring = '';
        return;
    end

    % otherwise cut string
    uzstring = uzstring(1:fzp-1);
end
